package co.fitstart.market.web.controller.questionnaire.rest;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.handler.CookieHandler;

import co.fitstart.entity.market.Questionnaire;
import co.fitstart.entity.market.QuestionnaireStat;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.UserAccount;
import co.fitstart.market.Constant;
import co.fitstart.market.entity.UserContext;
import co.fitstart.market.handler.SmsSender;
import co.fitstart.market.service.QuestionnaireService;
import co.fitstart.market.service.UserService;
import co.fitstart.market.web.resolver.Secure;

/**
 * 
 * @author dan
 *
 */
@RestController
@RequestMapping("/questionnaires")
public class QuestionnaireRestController {
    
    @Autowired
    private QuestionnaireService questionnaireService;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    private SmsSender smsSender;
    
    @Autowired
    private UserService userService;
    
    private static final Logger logger = LoggerFactory.getLogger(QuestionnaireRestController.class);
    
    /**
     * 
     * @param openid
     * @param stat
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public @ResponseBody String check(@CookieValue(name = "fitstart_test_openid", required = true) String openid,
                                      QuestionnaireStat stat) {
        Result result = new Result();
        
        try {
            questionnaireService.check(stat, openid);
            
            result.success().message("提交问卷成功");
            
        } catch (Exception e) {
            
            logger.error("check - ", e);
            result.success().message("提交问卷失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param mobile
     * @param code
     * @param token
     * @param userContext
     * @param httpSession
     * @param response
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody String onMobileLogin(@RequestParam("mobile") String mobile, 
                                              @RequestParam("code") String code, 
                                              @RequestParam("token") String token,
                                              UserContext userContext,
                                              HttpSession httpSession,
                                              HttpServletResponse response) {
        
        Result result = new Result();
        
        try {
            
            // check verify code first 
            boolean valid = smsSender.checkVerifyCode(mobile, code, token);

            if(valid) {
                
                String openid = userContext.getOpenid();
                String cookieAccountId = userContext.getAccountId();
                
                // 1. check userContext 
                if((StringUtils.isNotEmpty(openid) && StringUtils.isNotBlank(openid)) && (StringUtils.isEmpty(cookieAccountId) || StringUtils.isBlank(cookieAccountId))) {
                    logger.warn("LoginController#onMobileLogin login with cookie openid [{}], but cookieAccountId is empty. please check the wechatAuthorityInteceptor", openid);
                }
                
                // 2. do login with mobile, openid, accountId
                logger.info("LoginController#onMobileLogin login with mobile [{}] openid [{}] accountId [{}]", mobile, openid, cookieAccountId);
                UserAccount userAccount = userService.login(mobile, openid, cookieAccountId, false);
                if(userAccount == null) {
                    throw new BusinessException("用户手机账号保存失败");
                }
                
                // 3. add mobile & userAccount id into cookie
                String mobileAccountId = String.valueOf(userAccount.getId());
                if(StringUtils.isNotEmpty(mobileAccountId) && StringUtils.isNotBlank(mobileAccountId)) {
                    cookieHandler.addCookie(response, Constant.USER_ACCOUNT_KEY, mobileAccountId, 7200);
                }
                cookieHandler.addCookie(response, Constant.MOBILE_KEY, mobile, 7200);
                
                result.success().message("登录成功,正在生成课程,请稍后!");
            } else {
                
                result.fail().message("验证码不正确");
            }
            
            
        } catch (Exception e) {
            logger.error("QuestionnaireRestController#onMobileLogin() error", e);
            result.fail().message("绑定手机失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param email
     * @param userContext
     * @param httpSession
     * @param response
     * @return
     */
    @RequestMapping(value = "/email-register", method = RequestMethod.POST)
    public @ResponseBody String onEmailLogin(@RequestParam("email") String email,
    									     UserContext userContext,
    									     HttpSession httpSession,
    									     HttpServletResponse response) {
    	Result result = new Result();
    	
    	try {
    		

        	String openid = userContext.getOpenid();
            String cookieAccountId = userContext.getAccountId();
            
            // 1. check userContext 
            if((StringUtils.isNotEmpty(openid) && StringUtils.isNotBlank(openid)) && (StringUtils.isEmpty(cookieAccountId) || StringUtils.isBlank(cookieAccountId))) {
                logger.warn("LoginController#onMobileLogin login with cookie openid [{}], but cookieAccountId is empty. please check the wechatAuthorityInteceptor", openid);
            }
            
            // 2. do login with mobile, openid, accountId
            logger.info("LoginController#onMobileLogin login with email [{}] openid [{}] accountId [{}]", email, openid, cookieAccountId);
            UserAccount userAccount = userService.login(email, openid, cookieAccountId, true);
            if(userAccount == null) {
                throw new BusinessException("用户手机账号保存失败");
            }
            
            // 3. add mobile & userAccount id into cookie
            String mobileAccountId = String.valueOf(userAccount.getId());
            if(StringUtils.isNotEmpty(mobileAccountId) && StringUtils.isNotBlank(mobileAccountId)) {
                cookieHandler.addCookie(response, Constant.USER_ACCOUNT_KEY, mobileAccountId, 7200);
            }
            cookieHandler.addCookie(response, Constant.MOBILE_KEY, email, 7200);
            
            result.success().message("登录成功,正在生成课程,请稍后!");
        	
    		
    	} catch (Exception e) {
            logger.error("QuestionnaireRestController#onEmailLogin() error", e);
            result.fail().message("绑定手机失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    
    /**
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/course-create", method = RequestMethod.POST)
    public @ResponseBody String courseCreate(@Secure User user) {
        Result result = new Result();
        
        try {
            Questionnaire questionnaire = questionnaireService.load(user.getOpenid());
            
            questionnaireService.createCourse(questionnaire, user);
            
            result.success().message("生成课程成功");
            
        } catch (Exception e) {
            
            logger.error("courseCreate - ", e);
            result.success().message("生成课程失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
}
